package com.dgw.controller;

import com.dgw.dao.DepartmentDao;
import com.dgw.dao.EmployeeDao;
import com.dgw.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @program: spring-boot-web-restfulcrud
 * @description: EmployeeController
 * @author: Mr.Dai
 * @create: 2019-11-30 22:26
 **/
@RestController
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;
    /**
     * list页面
     */
    @GetMapping("/emps")
    public ModelAndView emps(){
        ModelAndView modelAndView = new ModelAndView("emps/list");
        modelAndView.addObject("emps",employeeDao.getAll());
        return modelAndView;
    }

    /**
     *
     * go to add页面
     */
    @GetMapping("/emp")
    public ModelAndView toAddPage(){
        ModelAndView modelAndView = new ModelAndView("emps/add");
        modelAndView.addObject("depts",departmentDao.getDepartments());
        return modelAndView;
    }

    /**
     *
     * save emp
     */
    @PostMapping("/emp")
    public ModelAndView saveEmployee(Employee employee){
        // 添加成功到 emps 下
        ModelAndView modelAndView = new ModelAndView("redirect:/emps");
        employeeDao.save(employee);
        return modelAndView;
    }

    /**
     * update emp 修改回显二合一 可以分离一个edit
     */
   @GetMapping("/emp/{id}")
    public ModelAndView updateEmployee(@PathVariable("id")Integer id){
        Employee employee = employeeDao.get(id);
        ModelAndView modelAndView = new ModelAndView("emps/add");
        modelAndView.addObject("emp",employee);
        modelAndView.addObject("depts",departmentDao.getDepartments());
        return modelAndView;
    }

    /**
     * 修改emp
     */
    @PutMapping("/emp")
    public ModelAndView updateEmployee(Employee employee){
        System.out.println(employee);
       employeeDao.save(employee);
        ModelAndView modelAndView = new ModelAndView("redirect:/emps");
        return modelAndView;
    }

    /**
     * delete emp
     */
    @PostMapping("/emp/{id}")
    public ModelAndView deleteEmployee(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        ModelAndView modelAndView = new ModelAndView("redirect:/emps");
        return modelAndView;
    }
}
